package filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

public class LoginFilter implements Filter {
	List<String> urlList = new ArrayList<String>();
	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		// 当前会话没有员工对象，并且访问的不是白名单
		if( (session.getAttribute("employee") == null) && !checkList(req.getRequestURI()) ) {
			// 重定向激发request过滤器--LoginFilter
			rep.sendRedirect(req.getContextPath() + "/error.html");
		} else {
			chain.doFilter(request, response);
		}
	}

	private boolean checkList(String servletPath) {
		if(urlList == null || urlList.size() < 1){
			return false;
		} else {
			for (String string : urlList) {
				if(servletPath.contains(string.trim())) {
					return true;
				}
			}
		}
		return false;
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// 加载初始化参数---白名单
		String url = filterConfig.getInitParameter("noCheck");
		if(StringUtils.isNoneBlank(url)) {
			if(StringUtils.indexOf(url, ",")!=-1) {
				// 多个url
				for (String string : url.split(",")) {
					urlList.add(string.trim());
				}
			} else {
				// 单个url
				urlList.add(url);
			}
			
		}
		
	}

}
